package game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class GomokuClient {
    private Socket socket;
    private PrintWriter out;
    private BufferedReader in;
    private JFrame frame;
    private JButton[][] buttons;
    private boolean isMyTurn;
    private char[][] board;
    private char mySymbol;

    public static void main(String[] args) {
        new GomokuClient().start();
    }

    public void start() {
        // 初始化棋盘
        board = new char[15][15];
        for (int i = 0; i < 15; i++) {
            for (int j = 0; j < 15; j++) {
                board[i][j] = '-';
            }
        }

        // 输入对方IP地址
        String serverIP = JOptionPane.showInputDialog("输入对方IP地址:");
        if (serverIP == null || serverIP.isEmpty()) return;

        // 连接服务器
        try {
            socket = new Socket(serverIP, 12345);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 读取先后手信息
            String firstMove = in.readLine();
            mySymbol = firstMove.equals("X") ? 'O' : 'X';
            isMyTurn = mySymbol == 'X';

            // 创建UI
            createUI();

            // 启动线程接收对方消息
            new Thread(() -> {
                try {
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        String[] parts = inputLine.split(",");
                        int row = Integer.parseInt(parts[0]);
                        int col = Integer.parseInt(parts[1]);
                        board[row][col] = (mySymbol == 'X') ? 'O' : 'X';
                        updateButtonText(row, col);
                        isMyTurn = true;
                        checkWin(row, col);
                    }
                } catch (IOException e) {
                    System.out.println("对方断开连接");
                }
            }).start();

        } catch (IOException e) {
            System.err.println("连接失败: " + e.getMessage());
        }
    }

    private void createUI() {
        frame = new JFrame("五子棋 - 客户端 (" + mySymbol + ")");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 600);
        frame.setLayout(new GridLayout(15, 15));

        buttons = new JButton[15][15];
        for (int i = 0; i < 15; i++) {
            for (int j = 0; j < 15; j++) {
                buttons[i][j] = new JButton();
                buttons[i][j].setPreferredSize(new Dimension(40, 40));
                final int row = i;
                final int col = j;
                buttons[i][j].addActionListener(e -> {
                    if (isMyTurn && board[row][col] == '-') {
                        board[row][col] = mySymbol;
                        updateButtonText(row, col);
                        out.println(row + "," + col);
                        isMyTurn = false;
                        checkWin(row, col);
                    }
                });
                frame.add(buttons[i][j]);
            }
        }

        frame.setVisible(true);
    }

    private void updateButtonText(int row, int col) {
        buttons[row][col].setText(String.valueOf(board[row][col]));
        buttons[row][col].setEnabled(false);
    }

    private void checkWin(int row, int col) {
        char symbol = board[row][col];
        if (checkDirection(row, col, 1, 0, symbol) || // 水平
                checkDirection(row, col, 0, 1, symbol) || // 垂直
                checkDirection(row, col, 1, 1, symbol) || // 对角线
                checkDirection(row, col, 1, -1, symbol)) { // 反对角线
            JOptionPane.showMessageDialog(frame, symbol + " 获胜！");
            frame.dispose();
            System.exit(0);
        }
    }

    private boolean checkDirection(int row, int col, int dRow, int dCol, char symbol) {
        int count = 1;
        for (int i = 1; i < 5; i++) {
            int r = row + i * dRow;
            int c = col + i * dCol;
            if (r < 0 || r >= 15 || c < 0 || c >= 15 || board[r][c] != symbol) break;
            count++;
        }
        for (int i = 1; i < 5; i++) {
            int r = row - i * dRow;
            int c = col - i * dCol;
            if (r < 0 || r >= 15 || c < 0 || c >= 15 || board[r][c] != symbol) break;
            count++;
        }
        return count >= 5;
    }
}
